package com.customers.service.Impl;

import com.customers.dao.UserDao;
import com.customers.entity.Message;
import com.customers.entity.User;
import com.customers.service.UserService;
import com.customers.util.ConnectJDBC;
import com.customers.util.StringUtil;

import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;

public class UserServiceImpl implements UserService {
    @Override
    public String toString() {
        return "UserServiceImpl{" +
                "userDao=" + userDao +
                '}';
    }

    public UserDao getUserDao() {
        return userDao;
    }

    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    private UserDao userDao;
    @Override
    public Message userlogin(User user,String sql) throws SQLException {
        Message message = new Message();

        //将用户输入信息存储起来
        message.setObject(user);

        if(StringUtil.isEmpty(user.getUsername()) || StringUtil.isEmpty(user.getPassword())){
            //判定获取的用户名和密码是否为空
            message.setCode(0);
            message.setMessage("用户名或密码不能为空");
            return message;
        }

        User u = null;
        try {
            u = userDao.searchUserByName(user,sql);
        } catch (SQLException e) {
            throw e;
        }


        if(u == null){
            message.setCode(0);
            message.setMessage("用户不存在");
            return message;
        }

        if(!user.getPassword().equals(u.getPassword())){
            message.setCode(0);
            message.setMessage("密码不正确");
            return message;
        }
        message.setObject(u);
        message.setMessage("登录成功");

        return message;
    }

    @Override
    public Message userRegister(User user,String searchSql,String registerSql) throws SQLException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        Message message = new Message();
        message.setObject(user);


        if(StringUtil.isEmpty(user.getUsername()) || StringUtil.isEmpty(user.getPassword())){
            //判定获取的用户名和密码是否为空
            message.setCode(0);
            message.setMessage("用户名或密码不能为空");
            return message;
        }

        User u = null;
        try {
            u = userDao.searchUserByName(user,searchSql);
        } catch (SQLException e) {
            throw e;
        }

        if(u.getUsername()!= null){
            message.setCode(0);
            message.setMessage("用户名已存在，请重新输入");
            return message;
        }

        try{
            userDao.queryUserByName(user,registerSql);
            ConnectJDBC.getConnection().commit();
        }catch (Exception e){
            ConnectJDBC.getConnection().rollback();
            throw e;
        }


        message.setObject(user);
        message.setMessage("注册成功，请返回登陆界面登录");

        return message;
    }
}
